<template>
  <div class="patient-reported-right">
    <div class="form">
      <template v-if="priority && priority.length > 0">
        <!--        <right-priority />-->
      </template>

      <template v-else>
        <!--        <right-analysis v-if="curMode === 0" />-->

        <!--        <template v-else-if="source && table">-->
        <!--          <right-form-->
        <!--            v-if="curMode === 1"-->
        <!--            :source="source"-->
        <!--            :original="original"-->
        <!--            :upVisitId="upVisitId"-->
        <!--            :manOptions="manOptions"-->
        <!--            :downVisitId="downVisitId"-->
        <!--            :changeSubjectId="changeSubjectId"-->
        <!--            @refreshSubjectInfo="refreshSubjectInfo"-->
        <!--            @formModify="formModify"-->
        <!--          />-->
        <!--          <right-list v-else-if="curMode == 2" :source="source" @upload="upload" />-->
        <!--        </template>-->
      </template>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapGetters, mapActions } from 'vuex'
// import RightForm from './components/form'
// import RightList from './components/list'
// import RightAnalysis from './components/analysis'
// import RightPriority from './components/priority'
import { cloneDeep } from 'lodash-es'
// import NProgress from 'nprogress'

export default {
  data() {
    return {
      source: null,
      original: null,
      version: 0,
      sourceList: [],
      list: null,
      upVisitId: '',
      downVisitId: '',
      curMode: 0,
      manOptions: []
    }
  },
  props: {
    changeSubjectId: {
      type: Number,
    },
  },
  // components: { RightForm, RightList, RightAnalysis, RightPriority },
  computed: {
    ...mapState({
      mode: state => state.treatment.mode,
      subjectInfo: state => state.treatment.subjectInfo,
      visit: state => state.treatment.visit,
      table: state => state.treatment.table,
      priority: state => state.treatment.priority,
    }),
    ...mapGetters({
      findRole: 'treatment/findRole',
    }),
    subtitle: function () {
      if (this.table && this.table.extandStatus && this.table.extandStatus.isLapse) {
        switch (this.table.extandStatus.isLapse) {
        case 2:
          return '本页已标注为“已失效”'
        case 4:
          return '本页已标注为“未采集”'
        case 5:
          return '本页已标注为“未发生”'
        }
      } else {
        return ''
      }
    },
  },
  watch: {
    table: {
      handler: function (val) {
        ++this.version
        this.source = null
        this.original = null
        if (val && val.relationType && val.relationType === 1) {
          this.findSubjectData(this.version)
        } else if (val && val.relationType && val.relationType === 2) {
          this.findSubjectDataList(this.version)
        }
      },
      deep: true,
      immediate: true,
    },
    mode: {
      handler: function (val) {
        if (val) {
          this.curMode = val
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    setTimeout(() => {
      this.getManList()
    }, 300)
  },
  methods: {
    ...mapActions('eCRFDetail', ['getSubjectData', 'getEmbeddedTable', 'subjectVisitTables', 'getSubjectDataList']),
    ...mapActions('centralManagement', ['getMemberManagementAPI']),
    ...mapMutations({
      clear: 'treatment/clear',
      setSource: 'treatment/setSource',
      setVisit: 'treatment/setVisit',
      setMode: 'treatment/setMode',
      setTable: 'treatment/setTable',
      setPriority: 'treatment/setPriority',
    }),

    // 获取研究者下拉数据
    async getManList() {
      const { coreId, id, databaseId, databaseVersion } = this.subjectInfo
      const params = {
        pageNo: 1,
        pageSize: 1000,
        projectId: localStorage.getItem('sys-project-id'),
        projectDatabaseId: localStorage.getItem('project-database-Id'),
        coreId,
      }
      const res = (await this.getMemberManagementAPI({ params })) || {}
      const data = res.data.records || []
      const list = []
      data && data.forEach(item => {
        const roleList = []
        item.roleList && item.roleList.forEach(item => {
          roleList.push(item.code)
        })
        if (roleList.includes('Site_PI')) {
          list.push({
            codeDescribe: item.nickname,
            codeValue: item.nickname
          })
        }
      })
      this.manOptions = list
    },

    findSubjectData(version) {
      NProgress.configure({ parent: '.patient-reported-right', showSpinner: false })
      NProgress.start()
      const subjectVisits = JSON.parse(localStorage.getItem('subjectVisits'))
      let listIndex = 0
      subjectVisits &&
      subjectVisits.forEach((item, index) => {
        if (item.id === this.visit.id) {
          listIndex = index
        }
      })
      this.upVisitId = subjectVisits && subjectVisits[listIndex - 1] && subjectVisits[listIndex - 1].id
      this.downVisitId = subjectVisits && subjectVisits[listIndex + 1] && subjectVisits[listIndex + 1].id
      const { id, databaseId, databaseVersion } = this.subjectInfo
      const data = {
        projectId: localStorage.getItem('sys-project-id'),
        databaseId,
        databaseVersion,
        subjectId: id,
        subjectTable: !this.table.extandStatus ? 'subjectTable' : this.table.id,
        subjectDataId: this.table && this.table.subjectDataIds && this.table.subjectDataIds[0],
        upVisitId: this.upVisitId,
        downVisitId: this.downVisitId,
        environment: localStorage.getItem('environment'),
        isSubjectInfo: !this.table.extandStatus ? '1' : null,
        roleCode: localStorage.getItem('projectRoleCode')
      }
      this.getSubjectData({ data })
        .then(res => {
          if (version === this.version) {
            const { code, data } = res
            if (code === 200) {
              this.source = data
              this.original = JSON.parse(JSON.stringify(data))
            }
          }
        })
        .finally(() => {
          NProgress.done()
        })
    },

    findSubjectDataList(version) {
      NProgress.configure({ parent: '.patient-reported-right', showSpinner: false })
      NProgress.start()
      const { id, databaseId, databaseVersion } = this.subjectInfo
      const data = {
        projectId: localStorage.getItem('sys-project-id'),
        databaseId,
        databaseVersion,
        subjectId: id,
        subjectTable: this.table.id,
        subjectDataIds: this.table.subjectDataIds,
        environment: localStorage.getItem('environment'),
        roleCode: localStorage.getItem('projectRoleCode')
      }
      this.getSubjectDataList({ data })
        .then(res => {
          if (version === this.version) {
            const { code, data } = res
            if (code === 200) {
              this.source = data
            }
          }
        })
        .finally(() => {
          NProgress.done()
        })
    },

    upload() {
      this.findSubjectVisitTables()
    },
    // 刷新受试者信息
    refreshSubjectInfo() {
      this.$emit('refreshSubject')
    },

    formModify(val) {
      this.$emit('currentFormModify', val)
    },

    // 获取访视列表数据
    findSubjectVisitTables() {
      const { id, databaseVersion } = this.subjectInfo
      const params = {
        subjectId: id,
        databaseVersion: databaseVersion,
        subjectVisitId: this.visit.id,
      }
      this.subjectVisitTables({ params })
        .then(res => {
          const { code, data } = res
          if (code === 200) {
            if (data && data.length > 0) {
              let table
              const cumTableId = localStorage.getItem('cumTableId')
              if (cumTableId) {
                table = data.filter(item => item.id == cumTableId)[0]
                this.setTable(table)
                // this.findSubjectData(this.version)
              }
            }
          }
        })
      // .catch(error => {
      //   this.$message.error(error)
      // })
      // .finally(() => {})
    },

    onclick: function () {
      this.clear()
      this.$router.go(-1) // 返回上一级页面
    },

    open: function (e) {
      let flag
      const classList = e.currentTarget.classList
      if (classList.contains('active')) {
        flag = true
        classList.remove('active')
      } else {
        flag = false
        classList.add('active')
      }
      this.$emit('callback', flag)
    },
  },
}
</script>

<style lang="scss" scoped>
.patient-reported-right {
  display: flex;
  flex-flow: column nowrap;

  > .header {
    flex: 50;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 1.8rem 0 1rem;
    border-bottom: 1px #ebeef5 solid;

    > div {
      background-repeat: no-repeat;
    }

    > .left {
      width: 50rem;
      text-align: left;
      font-size: 1rem;
      font-weight: 700;
      padding-left: 0.2rem;
    }

    .subtitle {
      font-size: 0.875rem;
      margin-left: 0.625rem;
      color: #f56c6c;
    }
  }
}

> .form {
  flex: 800;
}
</style>
